package com.xci.core.handler;

import com.xci.core.base.RestMessage;
import com.xci.core.helper.WebHelper;
import com.xci.core.internal.Const;
import com.xci.core.internal.Sys;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 根据请求类型处理404错误:
 * 如果是普通请求(浏览器),返回错误页面
 * 如果是Ajax请求,返回统一的Json错误
 */
@ApiIgnore
@RestController
public class NotFoundController implements ErrorController {
    private static final String ERROR_PATH = "/error";

    @ResponseStatus(value = HttpStatus.NOT_FOUND)//处理404错误
    @RequestMapping(value = ERROR_PATH)
    public Object handleError(HttpServletRequest request, HttpServletResponse response, Exception e) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        boolean isAjax = WebHelper.isAjax(request);
        boolean isApp = WebHelper.isApp(request);
        //request.getAttribute("javax.servlet.error.request_uri")
        if(isAjax || isApp) {
            return RestMessage.fail(Sys.setting().getWeb().getError404AjaxMessage());
            // return new BoolMessage(false, "抱歉，您要访问的页面没有找到。");
        }
        var url = Const.EMPTY;
        ModelAndView modelAndView = new ModelAndView();
        if(statusCode == 404){
            url = Sys.setting().getWeb().getError404Url();
        }else{
            url = Sys.setting().getWeb().getError500Url();
        }
        modelAndView.setViewName(url);
        // modelAndView.setViewName("error/error404");
        return modelAndView;
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}